package com.thti.mecool.client.activity;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.command.send.plan.PlanSend;
import com.thti.mecool.client.util.TimeUtil;
import com.thti.mecool.client.util.Util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoadingDialog extends Dialog {
	public LoadingDialog(Context context, int theme) {
		super(context, theme);
		this.context=context;
	}
	getDataOK gDataOK;
	public interface getDataOK{
		public void getDataOK(boolean isOK);
	}
	public void setIsOKListener(getDataOK gDataOK){
		this.gDataOK=gDataOK;
	}
	public LoadingDialog(Context context) {
		super(context);
		this.context=context;
	}
	private Context context;
	Toast t;ProgressBar pb;
	double progress=0;
	TextView tv;StringBuffer sb;
	String name;
	HashMap<String, Boolean> finishFlag;
	boolean isFinish;
	AlertDialog dialog;
	Timer timer;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==4){
			if(!isFinish)
			t.show();
			return false;
			}
		return super.onKeyDown(keyCode, event);
	}
private Runnable r=new Runnable() {
	@Override
	public void run() {
		if(judge()){
			finishFlag.put(name, true);
			if(progress>=99){
				isFinish=true;
				pb.setProgress((int) progress);
				handler.removeCallbacks(r);
				Util.sendToast(context, "获取数据成功");
				Thread t=new Thread(){
					@Override
					public void run() {
						try {
							sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						if(gDataOK!=null)
							gDataOK.getDataOK(true);
						dismiss();
					};
				};
				t.start();
			}else{
				handler.post(r);
			}
		}else{
			handler.postDelayed(r, 500);
		}
	}
};

private boolean judge(){
	if(BaseActivity.getDataFlag(HandlerConstant.PlanCommand)){
		BaseActivity.removeDataFlag(HandlerConstant.PlanCommand);
		progress+=100;
		pb.setProgress((int) progress);
		setOverText("任务管理");
		return true; 
	}
	if(BaseActivity.getDataFlag(HandlerConstant.WorkMemosCommand)){
		BaseActivity.removeDataFlag(HandlerConstant.WorkMemosCommand);
		progress+=100;
		pb.setProgress((int) progress);
		setOverText("工作备忘");
		return true;
	}
	if(BaseActivity.getDataFlag(HandlerConstant.getChannelCommand)){
		BaseActivity.removeDataFlag(HandlerConstant.getChannelCommand);
		progress+=100;
		pb.setProgress((int) progress);
		setOverText("备忘终端");
		return true;
	}
	if(BaseActivity.getDataFlag(HandlerConstant.CommandFail)){
		BaseActivity.removeDataFlag(HandlerConstant.CommandFail);
		sb.append("任务管理数据获取失败");
		tv.setText(sb.toString());
		progress+=100;
		pb.setProgress((int) progress);
		return true;
	}
return false;
}

android.content.DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case -1:
			dialog.dismiss();
			reset();
			startRefresh();
			break;
		default:
			dialog.dismiss();
			BaseActivity.exitApp();
			break;
		}
	}
};
Handler handler=new Handler(){
	@Override
	public void handleMessage(Message msg) {
		super.handleMessage(msg);
		switch (msg.what) {
		case 10:
			if(!isFinish)
			dialog.show();
			break;

		default:
			break;
		}
	}
};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DisplayMetrics dm=new DisplayMetrics();
		getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
		View v=getLayoutInflater().inflate(R.layout.mecool_loading, null);
		v.setLayoutParams(new LayoutParams(dm.widthPixels,dm.heightPixels));
		setContentView(v);
		tv=(TextView)findViewById(R.id.mecool_loading_text);
		pb=(ProgressBar)findViewById(R.id.pb);
		}
	private void startRefresh(){
		t=Toast.makeText(context, "正在更新数据", 3000);
		finishFlag=new HashMap<String, Boolean>();
		sb=new StringBuffer();
		timer=new Timer();
		dialog=
				new AlertDialog.Builder(context).setTitle("提示")
				.setMessage("数据获取失败！")
				.setNegativeButton("退出程序", dialogClickListener)
				.setPositiveButton("重试", dialogClickListener).create();
		dialog.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if(keyCode==4){
						BaseActivity.exitApp();
				}
				return false;
			}
		});
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(10);
			}
		}, 30000);
	}
	@Override
	protected void onStart() {
		startRefresh();
		handler.post(r);
		PlanSend.getPlan(BaseActivity.getCurrentUser().getLoginName(),TimeUtil.dateToYear());
//		WorkProjectSend.getProject(BaseActivity.getCurrentUser().getLoginName());
//		WorkmemoSend.searchWorkmemo(BaseActivity.getCurrentUser().getLoginName(), 0, 10);
		setText();
		super.onStart();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		reset();
		timer.cancel();
	}
	private void reset(){
		sb.delete(0, sb.length());
		finishFlag.clear();isFinish=false;name=null;tv.setText("");
		progress=0;
		pb.setProgress(0);
	}
	private void setText(){
		sb.append("正在获取数据……\n");
		tv.setText(sb.toString());
	}
	
	private void setOverText(String name){
		this.name=name;
		sb.append(name+"模块数据获取成功！\n");
		tv.setText(sb.toString());
	}
}
